<template>
  <view class="add-new-page">
    <!-- 顶部导航 -->
    <Navbar title="添加新设备" />
    
    <!-- 主要内容 -->
    <view class="content">
      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 设备编号 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">设备编号</text>
            <view class="scan-btn-wrap" @click="handleScan">
              <image src="/static/img/minePages/vscode.png" mode="widthFix" class="scan-icon" />
            </view>
          </view>
          <input 
            class="form-input" 
            v-model="formData.deviceId"
            placeholder="读取二维码得到的编号"
            placeholder-class="input-placeholder"
          />
        </view>

        <!-- WIFI账号 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">WIFI账号</text>
          </view>
          <input 
            class="form-input" 
            v-model="formData.wifiAccount"
            placeholder="请输入账号"
            placeholder-class="input-placeholder"
          />
        </view>

        <!-- WIFI密码 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">WIFI密码</text>
          </view>
          <input 
            class="form-input" 
            v-model="formData.wifiPassword"
            placeholder="请输入密码"
            placeholder-class="input-placeholder"
            password
          />
        </view>

        <!-- 所属位置 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">所属位置</text>
          </view>
              <view class="form-select" @click="showLocationPicker = true">
             <text class="select-text" :class="{ placeholder: !formData.location }">
               {{ formData.location || '请选择区域-楼层-房间' }}
             </text>
             <image src="/static/img/components/arrow.png" mode="widthFix" class="select-arrow" />
           </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-actions">
      <view class="submit-btn" @click="handleSubmit">添加</view>
    </view>

    <!-- 区域选择器 -->
    <tn-picker
      v-model:open="showLocationPicker"
      :data="locationPickerData"
      :immediate-change="false"
      :mask="true"
      :show-cancel="false"
      confirm-color="#268EDA"
      label-key="label"
      value-key="value"
      @confirm="onLocationConfirm"
    />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { toScanCode, scanAndParse } from '@/utils/scanCode'
import { createRequest } from '@/utils/request'
import Navbar from '@/components/Navbar.vue'

// 表单数据
const formData = ref({
  deviceId: '',
  wifiAccount: '',
  wifiPassword: '',
  location: '',
  regionCode: '', // 存储选中的区域代码
  regionId: ''    // 存储选中的区域ID
})

// 区域选择相关
const showLocationPicker = ref(false)
const locationPickerData = ref([])

// 设置状态栏样式
onMounted(() => {
  // 设置状态栏为深色背景，白色文字
  uni.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: '#172869'
  })
  
  // 获取区域选项数据
  fetchLocationOptionsData()
})

// 获取区域选项数据
const fetchLocationOptionsData = async () => {
  try {
    // 调用真实API获取区域数据
    const result = await createRequest(`/region/getRemainingHierarchyForMonitorDeviceAdd`)
    
    if (result.code === 200 && result.data) {
      // 将API返回的数据格式转换为picker组件需要的格式
      const transformedData = transformRegionData(result.data)
      locationPickerData.value = transformedData
    } else {
      console.error('获取区域数据失败:', result.msg)
      uni.showToast({ 
        title: '获取区域数据失败', 
        icon: 'none' 
      })
    }
  } catch (error) {
    console.error('获取区域选项数据失败:', error)
    uni.showToast({ 
      title: '获取区域数据失败', 
      icon: 'none' 
    })
  }
}

// 转换区域数据格式
const transformRegionData = (apiData) => {
  return apiData.map(region => {
    const transformedRegion = {
      label: region.regionName,
      value: region.regionCode,
      id: region.id,
      level: region.regionLevel
    }
    
    // 如果有子区域，递归转换
    if (region.child && region.child.length > 0) {
      transformedRegion.children = transformRegionData(region.child)
    }
    
    return transformedRegion
  })
}

// 处理扫码
const handleScan = async () => {
  try {
    const result = await scanAndParse({
      onlyFromCamera: true,
      scanType: ['qrCode']
    })
    
    // 将扫码结果填入设备编号输入框
    formData.value.deviceId = result.raw
    
  } catch (error) {
    uni.showToast({ 
      title: error.errMsg || '扫码失败，请重试', 
      icon: 'none' 
    })
  }
}

// 区域选择确认
const onLocationConfirm = (value, pickerItem) => {
  // 级联选择返回的是数组，取最后一个值作为选中的区域
  const selectedLocation = Array.isArray(value) ? value[value.length - 1] : value
  
  // 根据选中的值找到对应的区域信息
  const findRegionInfo = (data, targetValue) => {
    for (const item of data) {
      if (item.value === targetValue) {
        return {
          name: item.label,
          code: item.value,
          id: item.id
        }
      }
      if (item.children) {
        const found = findRegionInfo(item.children, targetValue)
        if (found) return found
      }
    }
    return null
  }
  
  const regionInfo = findRegionInfo(locationPickerData.value, selectedLocation)
  if (regionInfo) {
    formData.value.location = regionInfo.name
    formData.value.regionCode = regionInfo.code
    formData.value.regionId = regionInfo.id
  } else {
    formData.value.location = selectedLocation
    formData.value.regionCode = selectedLocation
    formData.value.regionId = ''
  }
  showLocationPicker.value = false
}

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.value.deviceId) {
    uni.showToast({ title: '请输入设备编号', icon: 'none' })
    return
  }
  if (!formData.value.wifiAccount) {
    uni.showToast({ title: '请输入WIFI账号', icon: 'none' })
    return
  }
  if (!formData.value.wifiPassword) {
    uni.showToast({ title: '请输入WIFI密码', icon: 'none' })
    return
  }
  if (!formData.value.location || !formData.value.regionCode) {
    uni.showToast({ title: '请选择所属位置', icon: 'none' })
    return
  }

  try {
    // 准备提交数据
    const submitData = {
      deviceId: formData.value.deviceId,
      wifiAccount: formData.value.wifiAccount,
      wifiPassword: formData.value.wifiPassword,
      regionCode: formData.value.regionCode,
      regionId: formData.value.regionId,
      regionName: formData.value.location
    }
    
    console.log('提交数据:', submitData)
    
    // 模拟提交请求
    // const result = await createRequest('/device/add', {
    //   method: 'POST',
    //   data: submitData
    // })
    
    // 模拟提交请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    uni.showToast({ title: '设备添加成功', icon: 'success' })
    
    // 延迟返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error('提交失败:', error)
    uni.showToast({ 
      title: '提交失败，请重试', 
      icon: 'none' 
    })
  }
}
</script>

<style scoped lang="scss">
.add-new-page {
  @include page-with-header;
  min-height: 100vh;
  background: #172869;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 30rpx;
}

.form-section {
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 40rpx;
  box-sizing: border-box;
}

.form-item {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.label-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

.scan-btn-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
}

.scan-icon {
  width: 44rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #fff;
  border: none;
  box-sizing: border-box;
  outline: none;
}

.input-placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.form-select {
  width: 100%;
  height: 80rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  padding: 0 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  box-sizing: border-box;
}

.select-text {
  font-size: 28rpx;
  color: #fff;
  flex: 1;
  
  &.placeholder {
    color: rgba(255, 255, 255, 0.5);
  }
}

.select-arrow {
  width: 24rpx;
  height: 24rpx;
}

.bottom-actions {
  width: 100%;
  height: 168rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.submit-btn {
  width: 686rpx;
  height: 80rpx;
  background: linear-gradient(90deg, #3a8dde 0%, #256bda 100%);
  color: #fff;
  font-size: 32rpx;
  border: none;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(58, 108, 255, 0.12);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:active {
    transform: scale(0.98);
  }
}

/* Picker组件样式优化 */
:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-picker__content) {
  background: #172869 !important;
  border-radius: 20rpx 20rpx 0 0 !important;
}

:deep(.tn-picker__header) {
  background: #172869 !important;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.tn-picker__confirm) {
  color: #1ec8e1 !important;
}

:deep(.tn-picker__cancel) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.tn-picker__title) {
  color: #fff !important;
}

:deep(.tn-picker-view__item) {
  color: #fff !important;
}

:deep(.tn-picker-view__item--selected) {
  color: #1ec8e1 !important;
}
</style>